#include "cs8tableview.h"

#include <QKeyEvent>
#include <QDebug>
#include <QMessageBox>
#include <QStringList>
#include "spinboxdelegate.h"
#include "sellermodel.h"

cs8TableView::cs8TableView(QWidget *parent) :
    QTableView(parent),
    m_addAutomaticRow(true)
{
    setItemDelegateForColumn (2,new SpinBoxDelegate(this,0));
    setItemDelegateForColumn (3,new SpinBoxDelegate(this,0));
    setItemDelegateForColumn (4,new SpinBoxDelegate(this,2,true));
    setItemDelegateForColumn (5,new SpinBoxDelegate(this,2,true));
    setTabKeyNavigation (true);

    m_filteredSellerModel=new QSortFilterProxyModel(this);
    m_filteredSellerModel->setFilterFixedString ("X");
    m_filteredSellerModel->setFilterCaseSensitivity (Qt::CaseInsensitive);
    m_salesPeriod=999;
}

void cs8TableView::setSellerModel(SellerModel *model)
{
    m_filteredSellerModel->setSourceModel (model);
}

void cs8TableView::clearSalesRows()
{
    m_salesModel->clear ();
    m_salesModel->setColumnCount (7);
    m_salesModel->setHorizontalHeaderLabels (QStringList() << trUtf8 ("POS") << trUtf8 ("Transaktion") << trUtf8 ("Verkäufer") << trUtf8 ("Anzahl") << trUtf8 ("Einzelpreis") << trUtf8 ("Summe") << trUtf8 ("Name") );
    emit salesCleared();
    /*
             *ui->cbNewSale->setEnabled (true);
            ui->cbCancelSale->setEnabled (false);
            ui->cbCompleteSale->setEnabled (false);
            ui->tableViewSales->setEnabled (false);
            ui->toolButtonRemoveLine->setEnabled (false);
            ui->lineEditTotal->setValue (0);
            ui->cbNewSale->setFocus ();
                    */
}


void cs8TableView::removeCurrentRow()
{
    QModelIndex index=currentIndex ();
    if (index.isValid())
    {
        int row=index.row();
        if (QMessageBox::question (this,
                                   trUtf8 ("Frage"),
                                   trUtf8 ("Soll die akutelle Zeile entfernt werden?"),
                                   QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
        {
            model()->removeRows (row,1);
        }
    }
}

void cs8TableView::keyPressEvent(QKeyEvent *event)
{
    if (event->key ()==Qt::Key_Return)
    {
        qDebug() << "cs8TableView: Key_Return";
        QKeyEvent event(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
        QTableView::keyPressEvent(&event);
    }
    else
    {
        QTableView::keyPressEvent (event);
    }
}
void cs8TableView::addEmptySalesRow()
{
    qDebug() << "adding empty row";
    if (!m_addAutomaticRow)
        return;
    //m_salesModel->blockSignals(true);
    //QStandardItemModel *m_salesModel=qobject_cast<QStandardItemModel*>(model());
    int row=model()->rowCount ();

    m_salesModel->insertRow (row);

    qDebug() << "salesModel: " << m_salesModel->rowCount () << "," << m_salesModel->columnCount ();
    m_salesModel->setData (m_salesModel->index (row,6),"");
    m_salesModel->setData (m_salesModel->index (row,5),"");
    m_salesModel->setData (m_salesModel->index (row,5),Qt::AlignCenter , Qt::TextAlignmentRole);
    m_salesModel->setData (m_salesModel->index (row,4),"");
    m_salesModel->setData (m_salesModel->index (row,4),Qt::AlignCenter, Qt::TextAlignmentRole);
    m_salesModel->setData (m_salesModel->index (row,3),"");
    m_salesModel->setData (m_salesModel->index (row,3),Qt::AlignCenter, Qt::TextAlignmentRole);
    m_salesModel->setData (m_salesModel->index (row,2),"0");
    m_salesModel->setData (m_salesModel->index (row,1),"0");
    m_salesModel->setData (m_salesModel->index (row,0),"0");
    m_salesModel->blockSignals (true);
    m_salesModel->setData (m_salesModel->index (row,3),"1");
    //model_->item (row,3)->setText ("1");
    m_salesModel->item (row,0)->setFlags (Qt::NoItemFlags);
    m_salesModel->item (row,1)->setFlags (Qt::NoItemFlags);
    m_salesModel->item (row,6)->setFlags (Qt::NoItemFlags);
    m_salesModel->item (row,5)->setFlags (Qt::NoItemFlags);
    m_salesModel->blockSignals (false);
    // m_salesModel->blockSignals(false);
}

void cs8TableView::slotItemChanged(QStandardItem *item)
{
    int row=item->row ();
    QString data=item->data (Qt::DisplayRole).toString().remove(trUtf8 ("€")).trimmed();

    if ((row==model()->rowCount ()-1) && (item!=0) && (data.toDouble ()>0))
    {
        addEmptySalesRow ();
    }

    QStandardItemModel* sellerModel=dynamic_cast<QStandardItemModel*>( m_filteredSellerModel->sourceModel ());
    if (!sellerModel)
        return;
    switch (item->column ())
    {
    // seller has changed, check if it exists
    case 2:
    {
        QString seller=item->text ();
        QBrush brush;
        QList<QStandardItem *> list=sellerModel->findItems (seller,Qt::MatchExactly,0);
        if (list.count ()==0)
        {
            brush.setColor (Qt::red);
            m_salesModel->item (row,6)->setText ("Unbekannt");
            m_salesModel->item (row,6)->setToolTip (trUtf8("Unbekannter Verkäufer"));
            m_salesModel->item (row,6)->setForeground (brush);
        }
        else
        {

            QString name=sellerModel->item (list.at(0)->row (),1)->text ();


            if ((m_salesPeriod!=999) && (sellerModel->item (list.at(0)->row (),2+m_salesPeriod)->text ().isEmpty ()) )
            {
                m_salesModel->item (row,6)->setText (trUtf8 ("NICHT AKTIV (%1)").arg(name));
                m_salesModel->item (row,6)->setToolTip (trUtf8("Verkäufer %1 ist in dieser Verkaufsperiode nicht aktiv!")
                                                        .arg(name)
                                                        );
                brush.setColor (Qt::darkYellow);
            }
            else
            {
                m_salesModel->item (row,6)->setToolTip ("");
                m_salesModel->item (row,6)->setText (name);
                brush.setColor (Qt::gray);
            }
            m_salesModel->item (row,6)->setForeground (brush);
        }
        resizeColumnToContents (6);
        //item->setForeground (brush);
        //item->setData (brush,Qt::BackgroundRole);
        break;
    }
        // quantity or amount has changed
    case 3:
    case 4:
    {
        if (m_salesModel->item (row,3)!=0 && m_salesModel->item (row,4)!=0)
        {
            QString qty=m_salesModel->item (row,3)->text ();
            QString amount=m_salesModel->item (row,4)->text ();
            amount.chop(1);
            double sum= qty.toDouble()*amount.toDouble();
            m_salesModel->item (row,5)->setText (trUtf8 ("%1 €").arg(sum,0,'f',2));
            calculateTotalSum();
        }
        break;
    }
    }
}

void cs8TableView::calculateTotalSum()
{
    double total=0;
    for (int row=0;row<model()->rowCount ();row++)
    {
        QString data=m_salesModel->item (row,5)->text ();
        data.remove(trUtf8 ("€"));
        total += data.toDouble ();
    }
    emit totalSumChanged (total);
}


void cs8TableView::setModel(QAbstractItemModel *model)
{
    QTableView::setModel (model);
    connect(model,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(slotItemChanged(QStandardItem*)));
    m_salesModel=qobject_cast<QStandardItemModel*>( model );
    clearSalesRows ();
}


void cs8TableView::setSalesPeriod(int value)
{
    m_salesPeriod=value;
    m_filteredSellerModel->setFilterKeyColumn (2+m_salesPeriod);
}

bool cs8TableView::loadPosFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open (QFile::ReadOnly))
        return false;

    clearSalesRows ();
    QStringList data=QString(file.readAll ()).split('\n');
    // remove header
    data.removeFirst();
    foreach(QString rowData,data)
    {
        m_salesModel->setRowCount (m_salesModel->rowCount ()+1);
        int row=m_salesModel->rowCount ()-1;
        QStringList items=rowData.split (";");

        if (items.count ()==6)
        {
            for (int col=0;col<items.count (); col++)
            {
                m_salesModel->blockSignals (true);
                m_salesModel->setItem (row,col,new QStandardItem(items[col]));
                // m_salesModel->setData (m_salesModel->index (row,col),items[col]);
                m_salesModel->blockSignals (false);
                //m_salesModel->item (row,col)->setText (items[col]);
            }
            m_salesModel->setItem (row,6,new QStandardItem());
            m_salesModel->item (row,0)->setFlags (0);
            m_salesModel->item (row,1)->setFlags (0);
            m_salesModel->item (row,6)->setFlags (0);
        }
        else
        {
            qDebug() << "skipped invalid line" << items;
            m_salesModel->removeRow (row);
        }
    }
    file.close ();
    for (int row=0;row<m_salesModel->rowCount ();row++)
    {
        if (m_salesModel->item (row,2))
            slotItemChanged (m_salesModel->item (row,2));
    }
    resizeColumnsToContents ();
    return true;
}

bool cs8TableView::savePosFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.remove ())
        return false;
    if (!file.open (QFile::WriteOnly))
        return false;

    QString header;
    header=trUtf8 ("POS;Transaktion;Verkäufer;Anzahl;Einzelpreis;Summe\n");
    file.write(header.toUtf8 ());

    for (int row=0;row<m_salesModel->rowCount ();row++)
    {
        QString data=m_salesModel->item (row,3)->text ();
        data.remove(trUtf8 ("€"));
        double sum=data.toDouble ();
        if (sum!=0)
        {
            QString line=QString("%1;%2;%3;%4;%5;%6\n")
                    .arg (m_salesModel->item (row,0)->text ())
                    .arg(m_salesModel->item (row,1)->text ())
                    .arg(m_salesModel->item (row,2)->text ())
                    .arg(m_salesModel->item (row,3)->text ())
                    .arg(m_salesModel->item (row,4)->text ().remove(trUtf8 ("€")))
                    .arg(m_salesModel->item (row,5)->text ().remove(trUtf8 ("€")));
            file.write (line.toUtf8 ());

        }
    }

    file.close ();

    return true;
}

void cs8TableView::setAddAutomaticRow(bool value)
{
    m_addAutomaticRow=value;
}

QSortFilterProxyModel *cs8TableView::sellerModel()
{
    return m_filteredSellerModel;
}
